#include <iostream>
#include <unistd.h>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "Common.hpp"
using namespace std;

int ShowBoard()
{
    cout << "*************************************" << endl;
    cout << "*************************************" << endl;
    cout << "**  0. mysql_task    1. net_task   **" << endl;
    cout << "**  2. sync_task     3. mysqk_quit **" << endl;
    cout << "**  4. net_quit      5. sync_quit  **" << endl;
    cout << "**  6. server_quit                 **" << endl;
    int command = 0;
    cin >> command;
    return command;
}
FifoName fifoname;
int main()
{
    // 创建命名管道
    for (int i = 0; i < fifoname._size; i++)
    {
        int n = mkfifo(fifoname._fifonames[i].c_str(), mode);
        if (n == -1)
        {
            cout << "server:: mkfifo filed";
            cout << strerror(errno) << endl;
            exit(1);
        }
    }
    cout << "creat fifo successful" << endl;
    // 打开命名管道
    int wfd[fifoname._size];
    for (int i = 0; i < fifoname._fifonames.size(); i++)
    {
        wfd[i] = open(fifoname._fifonames[i].c_str(), O_WRONLY);
        if (wfd[i] == -1)
        {
            cout << "server:: open filed";
            cout << strerror(errno) << endl;
            exit(1);
        }
    }
    cout << "open fifo successful " << endl;
    // 开始通信
    int index = 0;
    while(true)
    {
        int command = ShowBoard();

        if(command == 6)
            break;
        else if(command > 6 || command < 0)
            continue;
        
        int n = write(wfd[command % 3],&command,sizeof(int));
        switch(command)
        {
            case 3:
                index = 3%3;
                close(wfd[index]);
                unlink(fifoname._fifonames[index].c_str());
                break;
            case 4:
                index = 4%3;
                close(wfd[index]);
                unlink(fifoname._fifonames[index].c_str());
                break;
            case 5:
                index = 5%3;
                close(wfd[index]);
                unlink(fifoname._fifonames[index].c_str());
                break;
            default:
                break;
        }
        if(n == -1)
        {
            cout << "server:: write filed";
            cout << strerror(errno) << endl;
            exit(1);
        }

    }


    // 关闭文件
    for (int i = 0; i < fifoname._fifonames.size(); i++)
    {
        close(wfd[i]);
    }

    // 删除管道
    for (int i = 0; i < fifoname._fifonames.size(); i++)
    {
        unlink(fifoname._fifonames[i].c_str());
    }

    return 0;
}
